// AstNodeImpl.java
// Mac Radigan
// $Id: AstNodeImpl.groovy 39 2011-10-17 09:54:18Z mac.radigan $
package org.radigan.xom.impl

import org.radigan.xom.service.AstNode
import org.radigan.xom.service.Object

import javax.swing.tree.DefaultMutableTreeNode
import java.lang.StringBuffer
import java.net.URI

public class AstNodeImpl extends DefaultMutableTreeNode implements AstNode {
  private URI namespace
  private String type
  private String name
  private java.lang.Object value
  public AstNodeImpl(URI namespace, String type, String name, java.lang.Object value) {
    this.namespace = namespace
    this.type = type
    this.name = name
    this.value = value
  }
  public void setValue(java.lang.Object value) {
    this.value = value
  }
  public java.lang.Object getValue() {
    return value
  }
  public String getStringValue() {
    try {
      if(value in String) {
        return new String(value)
      } else {
        throw new Exception("Unhandled data type is not a String.")
      }
    } catch(e) {
      throw new Exception("Data type is not a String.")
    }
  }
  public String getIntegerValue() {
    try {
      if([Integer, int].find {value in it}) {
        return new Integer(value)
      } else if(value in String) {
        return Integer.parseInt(value)
      } else {
        throw new Exception("Unhandled data type is not a Integer.")
      }
    } catch(e) {
      throw new Exception("Data type is not a Integer.", e)
    }
  }
  public String getDoubleValue() {
    try {
      if([Double, double, Float, float].find {value in it}) {
        return new Double(value)
      } else if(value in String) {
        return Double.parseDouble(value)
      } else {
        throw new Exception("Unhandled data type is not a Double.")
      }
    } catch(e) {
      throw new Exception("Data type is not a Double.", e)
    }
  }
  public org.radigan.xom.service.Object getObjectValue() {
    if([org.radigan.xom.service.Object].find {value in it}) return value
    throw new Exception("Data type is not a XOM Object.")
  }
  public void setNamespace(URI namespace) {
    this.namespace = namespace
  }
  public URI getNamespace() {
    return namespace
  }
  public void setName(String name) {
    this.name = name
  }
  public String getName() {
    return name
  }
  public void setType(String type) {
    this.type = type
  }
  public String getType() {
    return type
  }
  String toString() {
    def sb = new StringBuffer()
    sb << " [${type}] ${name} (${value})" << "\n"
    for(AstNode astNode : children()) {
      sb << astNode.toString(2)
    }
    return sb.toString()
  }
  String toString(int indentLevel) {
    def sb = new StringBuffer()
    sb << """ """.multiply(indentLevel) << " [${type}] ${name} (${value})" << "\n"
    for(AstNode astNode : children()) {
      sb << """ """.multiply(indentLevel) << astNode.toString(indentLevel+2)
    }
    return sb.toString()
  }
}

// *EOF*
